<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警示框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <el-row>
        <el-col :span="3">选择商品分类:</el-col>
        <el-col :span="12">
          <!-- 选择分类级联选择器 -->
          <el-cascader
            :options="categoryList"
            :props="categoryProps"
            v-model="selectCateID"
            @change="selectCateChange"
            expand-trigger="hover"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-click="toggleList">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="selectCateID.length!==3"
            type="primary"
            @click="addParamsdialogVisible=true"
          >添加参数</el-button>
          <!-- 动态参数表格1 -->
          <el-table stripe border :data="paramsList">
            <el-table-column width="50px" type="expand">
              <template slot-scope="scope">
                <!-- 展开列渲染小tag，点击+newtag显示输入框 通过v-if else切换-->
                <!-- 有个bug,其他行的input框会受影响，所以每行是个独立的visible和value值 -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  v-show="item"
                  closable
                  @close="delTag(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="inpTag"
                  v-if="scope.row.visible"
                  v-model="scope.row.inputVal"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="addTag" size="small" @click="addTag(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50px"></el-table-column>
            <el-table-column label="参数名称" align="center" prop="attr_name"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="selectCateID.length!==3"
            type="primary"
            @click="addParamsdialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性表格2 -->
          <el-table stripe border :data="paramsList">
            <el-table-column width="50px" type="expand">
              <template slot-scope="scope">
                <!-- 展开列渲染小tag，点击+newtag显示输入框 通过v-if else切换-->
                <!-- 有个bug,其他行的input框会受影响，所以每行是个独立的visible和value值 -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  v-show="item"
                  closable
                >{{item}}</el-tag>
                <el-input
                  class="inpTag"
                  v-if="scope.row.visible"
                  v-model="scope.row.inputVal"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="addTag" size="small" @click="addTag(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50px"></el-table-column>
            <el-table-column label="属性名称" align="center" prop="attr_name"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/属性对话框，共用一个，需要切换文字 ，用计算属性-->
    <el-dialog
      :title="'添加'+dialogText"
      :visible.sync="addParamsdialogVisible"
      width="40%"
      @close="delAddParamsForm"
    >
      <el-form :rules="rules" :model="addParamsForm" ref="addParamsRef">
        <el-form-item :label="dialogText" prop="attr_name" label-position="left" label-width="80px">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAddParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+dialogText"
      :visible.sync="editParamsdialogVisible"
      width="40%"
      @close="delEditParamsForm"
    >
      <el-form :rules="rules" :model="editParamsForm" ref="editParamsRef">
        <el-form-item :label="dialogText" prop="attr_name" label-position="left" label-width="80px">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" editclass="dialog-footer">
        <el-button @click="editParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categoryList: [],
      // 配置级联选择器
      categoryProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectCateID: [],
      // 目前所选中的标签页
      activeTab: 'many',
      paramsList: [],
      // 添加参数
      addParamsdialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      // 修改参数
      editParamsForm: {
        attr_name: ''
      },
      // 要修改的参数的id
      ParamsID: '',
      editParamsdialogVisible: false,
      rules: {
        attr_name: [{ required: true, message: '必填项', trigger: 'blur' }]
      },
      // 点击添加小tag时显示输入框
      inputVisible: false,
      inputValue: ''
    }
  },
  created() {
    this.getGoodsCategories()
  },
  methods: {
    async getGoodsCategories() {
      const { data: ret } = await this.$http.get('categories')
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.categoryList = ret.data
    },
    async selectCateChange() {
      // 选择发生变化时 ，必须保证选择的是三级分类才能操作
      console.log(this.selectCateID)
      if (this.selectCateID.length !== 3) {
        // 清空所选id
        this.selectCateID = []
        // 清空表格
        this.paramsList = []
        return
      }
      // 发请求渲染列表
      this.getParamsList()
    },
    async toggleList() {
      // 切换tab栏是渲染不同的表格
      if (this.selectCateID.length !== 3) return
      this.getParamsList()
    },
    async getParamsList() {
      const { data: ret } = await this.$http.get(
        'categories/' + this.categoryID + '/attributes',
        { params: { sel: this.activeTab } }
      )
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      // 其他行的input框会受影响，所以要为每行设置独立的visible和value值
      ret.data.forEach(item => {
        item.attr_vals = item.attr_vals.split(',')
        item.visible = false
        item.inputVal = ''
      })
      this.paramsList = ret.data
      console.log(this.paramsList)
    },
    doAddParams() {
      // 发请求完成添加参数
      this.addParamsdialogVisible = false
      this.$refs.addParamsRef.validate(async val => {
        if (!val) return
        const { data: ret } = await this.$http.post(
          `categories/${this.categoryID}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeTab
          }
        )
        if (ret.meta.status !== 201) return this.$message.error(ret.meta.msg)
        this.$message.success(ret.meta.msg)
        this.getParamsList()
      })
    },
    delAddParamsForm() {
      this.$refs.addParamsRef.resetFields()
    },
    delEditParamsForm() {
      this.$refs.editParamsRef.resetFields()
    },
    async showEditParamsDialog(id) {
      // 显示修改对话框，显示当前参数/属性
      this.ParamsID = id
      this.editParamsdialogVisible = true
      const { data: ret } = await this.$http.get(
        `categories/${this.categoryID}/attributes/${id}`,
        {
          params: { sel: this.activeTab }
        }
      )
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      console.log('参数', ret.data)
      this.editParamsForm.attr_name = ret.data.attr_name
    },
    doEditParams() {
      this.editParamsdialogVisible = false
      this.$refs.editParamsRef.validate(async val => {
        if (!val) return
        const { data: ret } = await this.$http.put(
          `categories/${this.categoryID}/attributes/${this.ParamsID}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeTab
          }
        )
        if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
        this.$message.success(ret.meta.msg)
        this.getParamsList()
      })
    },
    delParams(id) {
      // 删除属性
      this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: ret } = await this.$http.delete(
            `categories/${this.categoryID}/attributes/${id}`
          )
          if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getParamsList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    addTag(row) {
      // 展开列添加小标签，变成输入框
      console.log(123)
      row.visible = true
      this.$nextTick(_ => {
        // $nextTick,页面被渲染更新后执行回调函数
        // 自动获取焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm(row) {
      // input框失去焦点时，添加到数组中
      if (!row.inputVal.trim()) {
        row.visible = false
        row.inputVal = ''
        return
      }
      row.attr_vals.push(row.inputVal)
      row.visible = false
      row.inputVal = ''
      // 重新提交
      this.doEditTags(this.categoryID, row)
    },
    delTag(i, row) {
      // 点击x删除小标签,通过索引删
      row.attr_vals.splice(i, 1)
      // 重新提交
      this.doEditTags(this.categoryID, row)
    },
    async doEditTags(id, row) {
      // 发请求提交修改的展开列下的小标签
      const { data: ret } = await this.$http.put(
        `categories/${id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_vals: row.attr_vals.join(','),
          attr_sel: row.attr_sel
        }
      )
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.$message.success(ret.meta.msg)
    }
  },
  computed: {
    // 获取分类id
    categoryID() {
      if (this.selectCateID.length !== 3) return null
      return this.selectCateID[this.selectCateID.length - 1]
    },
    dialogText() {
      return this.activeTab === 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>

<style lang='less' scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-row {
  display: flex;
  align-items: center;
}
.el-tabs {
  margin-top: 15px;
}
.inpTag {
  width: 120px;
}
</style>
